// comm.hpp
#ifndef __COMM_HPP__
#define __COMM_HPP__

#include "log.hpp"
#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
using namespace std;

// 共享内存的大小一般建议是4096的整数倍
// 如果定义成4097，实际上操作系统会给4096*2的大小，但又只能用4097，剩下的浪费
const int size = 4096;
const string pathname = "/home/sz/lesson32";
const int proj_id = 0x2222;
Log log(Onefile);

key_t GetKey()
{
    key_t k = ftok(pathname.c_str(), proj_id);
    if (k == -1)
    {
        log(Fatal, "ftok error: %s", strerror(errno));
        exit(1);
    }
    log(Info, "ftok success, key is: 0x%x", k); // %x，十六进制打印
    return k;
}

int GetShareMemHelper(int flag)
{
    key_t k = GetKey();
    int shmid = shmget(k, size, flag);
    if (shmid == -1)
    {
        log(Fatal, "create share memory error: %s", strerror(errno));
        exit(2);
    }
    log(Info, "create share memory success, shmid is: %d", shmid);
    return shmid;
}

// 一个进程创建
int Createshm()
{
    return GetShareMemHelper(IPC_CREAT | IPC_EXCL | 0666);
}

// 剩下的进程获取
int Getshm()
{
    // return GetShareMemHelper(0);  // 直接设置为0的话，表示只是获取，如果没有也不会创建，而是获取失败返回-1
    return GetShareMemHelper(IPC_CREAT);
}

#define FIFO_FILE "./myfifo"
#define MODE 0664

enum
{
    FIFO_CREATE_ERR = 1,
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR
};

class Init
{
public:
    Init()
    {
        // 创建管道文件
        int n = mkfifo(FIFO_FILE, MODE);
        if (n == -1)
        {
            // printf("%d: %s\n", errno, strerror(errno));
            //perror("mkfifo");
            //Log(Onefile).logmessage(Fatal, "error string: %s, error code: %d", strerror(errno), errno);
            Log(Classfile)(Fatal, "error string: %s, error code: %d", strerror(errno), errno);
            exit(FIFO_CREATE_ERR);
        }
    }
    ~Init()
    {
        // 删除管道文件
        int m = unlink(FIFO_FILE);
        if (m == -1)
        {
            //perror("unlink");
            //Log(Onefile).logmessage(Fatal, "error string: %s, error code: %d", strerror(errno), errno);
            Log(Classfile)(Fatal, "error string: %s, error code: %d", strerror(errno), errno);
            exit(FIFO_DELETE_ERR);
        }
    }
};

#endif